package Extends.CUICompents.CEffect 
{
	import Extends.CustomApp.CustomEvent;
	
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Timer;

	/**
	 * ...
	 * @author JeffXun
	 */
	public class CAutoMove extends CEffect 
	{
		static public const EFFECT_EVENT_MOVE_END:String = "EFFECT_EVENT_MOVE_END";
		
		static protected var TimeFraps:Number = 100;
		
		public var xFrom:Number = 0;
		public var xTo:Number   = 0;
		public var yFrom:Number = 0;
		public var yTo:Number   = 0;
		
		private var xSpeed:Number = 0;
		private var ySpeed:Number = 0;
		
		private var ms_rect:Rectangle = new Rectangle();
		public function CAutoMove(target:*,moveLine:* = null) 
		{
			super(target);
			
		}
		
		public function Play():void 
		{
			xSpeed = (xTo - xFrom) >= 0?20: -20;
			ySpeed = (yTo - yFrom) >= 0?20: -20;
			if (xSpeed != 0  || ySpeed != 0)
			{
				ms_Timer = new Timer(TimeFraps);
				ms_Timer.addEventListener(TimerEvent.TIMER, OnTimer);
				ms_Timer.start();
			}
		}
		
		public function get running():Boolean
		{
			return ms_Timer?ms_Timer.running:false;
		}
		
		private function checkEnd(cx:Number,cy:Number):Boolean
		{
			var pt:Point = ms_Target.getPos();
			if (xSpeed > 0 && cx >= xTo)
			{
				xSpeed = 0;
			}
			if (xSpeed < 0 && cx <= xTo)
			{
				xSpeed = 0;
			}
			
			if (ySpeed > 0 && cy >= yTo)
			{
				ySpeed = 0;
			}
			if (ySpeed < 0 && cy <= yTo)
			{
				ySpeed = 0;
			}
			
			if ((pt.x == xTo && pt.y == yTo) || (xSpeed==0 && ySpeed==0))
			{
				return false;
			}
			return true;
		}
		private function OnTimer(evt:TimerEvent):void
		{
			var oldPt:Point = ms_Target.getPos();
			var newX:Number = oldPt.x + xSpeed;
			var newY:Number = oldPt.y + ySpeed;
			if(ms_Target.isInRect(newX,newY) && this.checkEnd(newX,newY))
			{
				ms_Target.setPos(newX,newY);
			}
			else
			{
				//ms_Target.setPos(xTo,yTo);
				this.End();
			}
		}
		
		public function End():void
		{
			if (ms_Timer && ms_Timer.running)
			{
				ms_Timer.stop();
			}
			ms_Timer = null;
			this.dispatchEvent(new CustomEvent(EFFECT_EVENT_MOVE_END));
		}
	}

}